package com.vcaresolution.logistic.dao;

import java.io.Serializable;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;

/**
 * The <code>BaseDAOImpl</code> is a Repository which injects
 * DataSource used by <b>JdbcTemplate</b>.
 *
 * @author Snehal Shah
 * @version 1.0
 * @since ShipSoft 1.0
 */
@Repository
public class BaseDAO{

	
	protected SessionFactory sessionFactory;
	
	@Resource(name="sessionFactory")
	public void setSessionFactory(SessionFactory sessionFactory) {
		System.out.println("Session Factory :: "+sessionFactory);
		
		this.sessionFactory = sessionFactory;
	}

	public void add(Object transientInstance) {
		try {
			sessionFactory.getCurrentSession().persist(transientInstance);
		} catch (RuntimeException re) {
			re.printStackTrace();
			throw re;
		}
	}
	
	public Serializable insert(Object transientInstance) {
		try {
			return sessionFactory.getCurrentSession().save(transientInstance);
		} catch (RuntimeException re) {
			re.printStackTrace();
			throw re;
		}
	}
	
	public void update(Object instance) {
		try {
			sessionFactory.getCurrentSession().saveOrUpdate(instance);
		} catch (RuntimeException re) {
			re.printStackTrace();
			throw re;
		}
	}
	
	public void delete(Object persistentInstance) {
		try {
			sessionFactory.getCurrentSession().delete(persistentInstance);
		} catch (RuntimeException re) {
			re.printStackTrace();
			throw re;
		}
	}
	
	@SuppressWarnings("unchecked")
	public  <T> T findById(Class<T> objectClass, Serializable id) 
	{
		try 
		{
			T instance = (T) sessionFactory.getCurrentSession().get(objectClass, id);
			return instance;
		} 
		catch (RuntimeException re) 
		{
			re.printStackTrace();
			throw re;
		} 
	}
	
	@SuppressWarnings("unchecked")
	public <T> List<T> findByAll(Class<T> objectClass) {
		try {
			List<T> results = (List<T>) sessionFactory
					.getCurrentSession()
					.createCriteria(objectClass).list();
			
			return results;
		} catch (RuntimeException re) {
			re.printStackTrace();
			throw re;
		}
	}
}
